"""
Pytagram test suite.

This file is intended to be ran separately from pytagram.
"""

import unittest
import tempfile
import os

from options import Options
from drawer import Drawer
from parser import Parser, ParseException

class TestParser(unittest.TestCase):
    def testExamples(self):
        """
        Check out that the parser parses correctly all the example files
        """
        for item in os.listdir('examples'):
            if item.endswith('.tree'):
                path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'examples')
                path = path + os.sep + item
                parsed = Parser(path).parse()
                self.failIf(parsed == None, "Parsed object can't be empty")

    def testNonexistentFile(self):
        """
        Parser must raise IOError when the file doesn't exists
        """
        callable = Parser("nothere").parse
        self.assertRaises(IOError, callable)

    def testInvalidFile(self):
        """
        Parser must raise a ParseException when the file is invalid
        """

        # empty file
        emptyfile, name_emptyfile = tempfile.mkstemp()
        callable1 = Parser(name_emptyfile).parse
        self.assertRaises(ParseException, callable1)
        os.remove(name_emptyfile)

        # invalid file
        invalidfile, name_invalidfile = tempfile.mkstemp()
        f = open(name_invalidfile, 'w')
        f.write("'invalid")
        f.close()
        callable2 = Parser(name_invalidfile).parse
        self.assertRaises(ParseException, callable2)
        os.remove(name_invalidfile)


    def testInvalidIndentation(self):
        """
        Test that a file with an invalid indentation raises an ParseException
        """
        invalidfile, name_invalidfile = tempfile.mkstemp()
        f = open(name_invalidfile, 'w')
        f.write(""" \
* test
** test2
*** test3
!!!! test4
""")
        f.close()
        callable = Parser(name_invalidfile).parse
        self.assertRaises(ParseException, callable)
        os.remove(name_invalidfile)


class TestDrawer(unittest.TestCase):
    def testExamples(self):
        """
        Test that all the examples give correct output
        """
        for item in os.listdir('examples'):
            if item.endswith('.tree'):
                path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'examples')
                path = path + os.sep + item
                parsed = Parser(path).parse()

                o = Options()
                o['output'] = 'test.svg'
                o['width'] = 100
                o['height'] = 200
                o['step'] = 30
                o['bg_namespace'] = o['bg_class'] = o['bg_func'] = '#FFFFFF'
                o['fg_namespace'] = o['fg_class'] = o['fg_func'] = '#FFFFFF'

                d = Drawer(parsed, o).draw()
                os.remove("test.svg")

                self.failIf(d == False, "Draw result is false")




if __name__ == '__main__':
    unittest.main()
